//
//  UIImage+Scale.swift
//  EasyEverything
//
//  Created by YangZhe on 17/4/1.
//  Copyright © 2017年 kuletech. All rights reserved.
//

import Foundation
extension UIImage {
    
    ///对指定图片进行拉伸
    open func yResizableImage(name: String) -> UIImage {
        
        var normal = UIImage(named: name)!
        let imageWidth = normal.size.width * 0.5
        let imageHeight = normal.size.height * 0.5
        normal = resizableImage(withCapInsets: UIEdgeInsets(top: imageHeight, left: imageWidth, bottom: imageHeight, right: imageWidth))
        
        return normal
    }
    
    /**
     *  压缩上传图片到指定字节
     *
     *  image     压缩的图片
     *  maxLength 压缩后最大字节大小
     *
     *  return 压缩后图片的二进制
     */
//    open func yCompressImage(image: UIImage, maxLength: Int) -> UIImage {
//
//        let newSize = self.yScaleImage(image: image, imageLength: YConfig.imageMaxSize)
//        let newImage = self.yResizeImage(image: image, newSize: newSize)
//
//        var compress:CGFloat = 0
//        var data = UIImageJPEGRepresentation(newImage, compress)!
//
//        while data.count > maxLength && compress < 1 {
//            compress += 0.1
//            data = UIImageJPEGRepresentation(newImage, compress)!
//        }
//
//        return UIImage(data: data)!
//    }
    
    /**
     *  通过指定图片最长边，获得等比例的图片size
     *
     *  image       原始图片
     *  imageLength 图片允许的最长宽度（高度）
     *
     *  return 获得等比例的size
     */
    open func  yScaleImage(image: UIImage, imageLength: CGFloat) -> CGSize {
        
        var newWidth:CGFloat = 0.0
        var newHeight:CGFloat = 0.0
        let width = image.size.width
        let height = image.size.height
        
        if (width > imageLength || height > imageLength){
            
            if (width > height) {
                
                newWidth = imageLength
                newHeight = newWidth * height / width
                
            }else if(height > width){
                
                newHeight = imageLength
                newWidth = newHeight * width / height
                
            }else{
                
                newWidth = imageLength
                newHeight = imageLength
            }
            
        }else{
            newWidth = width
            newHeight = height
        }
        return CGSize(width: newWidth, height: newHeight)
    }
    
    /**
     *  获得指定size的图片
     *
     *  image   原始图片
     *  newSize 指定的size
     *
     *  return 调整后的图片
     */
    open func yResizeImage(image: UIImage, newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(newSize)
        image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
}
